<template>
  <!-- 特殊作业待办 -->
  <view v-if="isEmpty">
    <empty></empty>
  </view>
  <view v-else>
    <view class="cu-card-wrap" v-for="(item, index) in listData" :key="item.nodeTaskId">
      <view class="header-wrap">
        <view class="title-wrap">
          <text class="title">{{ item.ticketCode }}</text>
        </view>
      </view>
      <view class="affix">
        <image
          class="affix-icon"
          :src="`/static/images/ticket-type/work-type-${item.workTypeFlag}.png`"
          mode="aspectFit"
        />
      </view>
      <view class="body-wrap">
        <view class="content-wrap">
          <view class="label">作业项目：</view>
          <view class="value">{{ item.projectName }}</view>
        </view>
        <view class="content-wrap">
          <view class="label">项目编号：</view>
          <view class="value">{{ item.projectCode }}</view>
        </view>
        <view class="content-wrap">
          <view class="label">当前节点：</view>
          <view class="value">{{ item.nodeTypeLabel }}</view>
        </view>
        <view class="content-wrap">
          <view class="label">当前状态：</view>
          <view class="value" :class="{ 'color-A14430': item.pause !== '2' }">{{ item.pauseLabel }}</view>
        </view>

        <view class="content-wrap">
          <view class="label">作业票证：</view>
          <navigator :url="`/pages/jobSlip/detail/index?ticketId=${item.ticketId}`" class="value color-88B4C4">
            查看详情
            <image class="icon-more" src="/static/images/more.png" />
          </navigator>
        </view>
      </view>
      <view class="footer-wrap">
        <view class="button-wrap button-wrap-todo">
          <view class="button-wrap-left">
            <cu-dropdown
              v-if="item.nodeTypeFlag === nodeTypeFlagEnum.ACCEPT && item.assignee === staffId"
              style="z-index: 90"
            >
              <view class="more-button">更多</view>
              <template #dropdown>
                <cu-dropdown-item v-if="item.canAnalyse" @click="goInspect(item)">分析</cu-dropdown-item>
                <cu-dropdown-item @click="showSignature(item)">新增作业人员</cu-dropdown-item>
                <!--1031: 取消更换监护人入口-->
                <!--<cu-dropdown-item @click="showUserSelect(item)">更换监护人</cu-dropdown-item>-->
              </template>
            </cu-dropdown>
          </view>
          <view class="flex">
            <template v-if="item.canPauseOrStart">
              <view v-if="item.pause === '2'" class="button status-button active" @click="goPage(item, 'pause')"
                >暂停</view
              >
              <view v-if="item.pause === '1'" class="button status-button" @click="goPage(item, 'start')"> 启动</view>
            </template>
            <view
              v-if="
                item.nodeTypeFlag === nodeTypeFlagEnum.ANALYSE &&
                (item.workTypeFlag === specialWorkTypeEnum.FIRE ||
                  item.workTypeFlag === specialWorkTypeEnum.LIMIT_SPACE ||
                  item.workTypeFlag === specialWorkTypeEnum.ELECTRIC)
              "
              class="button"
              @click="transferTicket(item)"
            >
              转办
            </view>
            <template v-if="item.assignee === staffId && item.pause === '2'">
              <view
                v-if="item.nodeTypeFlag !== nodeTypeFlagEnum.ACCEPT"
                class="button"
                @click="goPage(item, item.nodeTypeFlag, item.btnLabel)"
              >
                {{ item.btnLabel }}
              </view>
              <view v-if="item.nodeTypeFlag === nodeTypeFlagEnum.ACCEPT" class="button" @click="goAcceptance(item)">
                验收
              </view>
            </template>
          </view>
        </view>
      </view>
    </view>
    <user-selector ref="userSelectorRef" @change="userSelectorChange" />
    <user-selector ref="transferSelectorRef" @change="transferSelectorChange" post-name="分析工" />
    <Signature
      ref="signature"
      v-model="signatureUrl"
      auto-upload
      @success="onSignatureSuccess"
      @close="isPullDown(true)"
    />
  </view>
</template>

<script>
import Empty from '@/components/cu-empty/index.vue'
import Signature from '@/pages/jobSlip/components/ContinueSign.vue'
import UserSelector from '@/components/user-selector/index.vue'
import CuUserSelector from '@/components/CuUserSelector/index.vue'
import { getSpecialWorkTodo, turnTicket } from '@/api/spw/project.js'
import { saveTicketInspect } from '@/api/spw/ticketInspect.js'
import { addWorkPersonal, updateGuardian } from '@/api/spw/ticketPerform.js'
import { actNodePermissionEnum, specialWorkTypeEnum, nodeTypeFlagEnum } from '@/utils/constant.js'
import { mapGetters } from 'vuex'
import CuDropdown from '@/components/cu-dropdown/index.vue'
import CuDropdownItem from '@/components/cu-dropdown/cu-dropdown-item.vue'
import { poiValid } from '../../api/spw/project'

export default {
  components: {
    Empty,
    UserSelector,
    CuUserSelector,
    Signature,
    CuDropdownItem,
    CuDropdown
  },
  computed: {
    ...mapGetters(['staffId']),
    isEmpty() {
      return this.isFinished && !this.listData.length
    }
  },
  data() {
    return {
      nodeTypeFlagEnum,
      specialWorkTypeEnum,
      signatureUrl: '',
      textColor: true,
      listData: [],
      isFinished: false,
      loading: false,
      pageNum: 1,
      addPersonalForm: {
        ticketId: ''
      },
      signType: 1, // 1 新增作业人 2 更换监护人
      changeGuardianForm: {
        staffId: '',
        taskId: '',
        ticketId: ''
      },
      transferForm: {}
    }
  },
  onLoad() {
    this.getList()
  },
  onPullDownRefresh() {
    this.reloadData()
  },
  onReachBottom() {
    this.getList()
  },
  methods: {
    // 禁止下拉刷新
    isPullDown(isPull) {
      //获取当前 Webview 窗口对象
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      const currentWebview = page.$getAppWebview && page.$getAppWebview()
      //根据状态值来切换禁用/开启下拉刷新
      currentWebview?.setStyle({
        pullToRefresh: {
          support: isPull,
          // style: plus.os.name === 'Android' ? 'circle' : 'default',
          style: 'circle'
        }
      })
    },
    initData() {
      this.pageNum = 1
      this.getList()
    },
    reloadData() {
      this.isFinished = false
      this.loading = false
      this.initData()
    },
    async getList() {
      if (this.isFinished || this.loading) {
        return
      }
      this.loading = true
      const { rows, total } = await getSpecialWorkTodo({
        pageNum: this.pageNum
      }).finally(() => {
        this.loading = false
      })

      rows.map((item) => {
        const guardianIds = item.guardianIds?.split(',') ?? []
        const nodePermissions = item.nodePermissions?.split(',') ?? []
        // 当前节点必须有暂停权限，监护人和节点审查人才能暂停和启动
        if (nodePermissions.includes(actNodePermissionEnum.PAUSE) && item.assignee === this.staffId) {
          item.canPauseOrStart = true
        }
        item.btnLabel = '处理'
        if (item.nodeTypeFlag === this.nodeTypeFlagEnum.ANALYSE) {
          item.btnLabel = '分析'
        }
        if ([this.nodeTypeFlagEnum.ACCEPT].includes(item.nodeTypeFlag)) {
          item.btnLabel = item.nodeTypeLabel
        }
        item.canAnalyse = [
          specialWorkTypeEnum.FIRE,
          specialWorkTypeEnum.LIMIT_SPACE,
          specialWorkTypeEnum.ELECTRIC
        ].includes(item.workTypeFlag)

        return item
      })
      this.listData = this.pageNum === 1 ? rows : [...this.listData, ...rows]
      this.isFinished = this.listData.length >= total
      this.pageNum += 1
      uni.stopPullDownRefresh()
    },

    /**
     * @description 校验定位
     */
    async positionValidate(ticketId) {
      // true 不可以处理
      // false 可以处理
      /*
       * 0 未定义围栏 1 已到排查区域 4 忽略校验
       * */
      let { data } = await poiValid(ticketId)
      if (data.code === 0 || data.code === 1 || data.code === 4) {
        return false
      } else {
        this.$modal.showToast(data.title)
        return true
      }
    },

    /**
     * @description 执行
     */
    execute(row, index) {
      this.currentRow = row
      this.excuteHandle()
    },
    /**
     * @description  执行
     */
    async excuteHandle() {
      const req = {
        reviewResult: actNodePermissionEnum.AGREE,
        reviewDescription: '通过',
        targetNodeId: '',
        targetNodeName: '',
        candidateId: '',
        candidateName: '',
        nodeId: this.currentRow.nodeId,
        nodeType: this.currentRow.nodeTypeValue,
        procInsId: this.currentRow.procInsId,
        nodeName: this.currentRow.nodeName,
        ticketId: this.currentRow.ticketId
      }
      await saveTicketInspect(this.currentRow.nodeTaskId, req)
      this.$modal.showToast('执行成功')
      this.reloadData()
    },
    /**
     * @description 根据不同的节点类型跳转对应的目标页面
     */
    async goPage(row, type, btnLabel) {
      let rew = null
      if (btnLabel !== '分析') {
        rew = await this.positionValidate(row.ticketId)
      }

      if (rew) return

      // 执行不需要签字
      if (type === '8') {
        this.execute(row)
        return
      }

      let url = ''
      switch (type) {
        // case '9':
        // 	url = '/pages/jobSlip/execute/submitForInspection';
        // 	break;
        case this.nodeTypeFlagEnum.ACCEPT:
          url = '/pages/jobSlip/execute/acceptance'
          break
        case 'start':
          url = '/pages/jobSlip/spw-status/start'
          break
        case 'pause':
          url = '/pages/jobSlip/spw-status/pause'
          break
        default:
          url = '/pages/jobSlip/check/inspect'
          break
      }
      uni.navigateTo({
        url: `${url}?nodeTaskId=${row.nodeTaskId}&ticketId=${row.ticketId}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          'callback:success': (data) => {
            if (data) {
              this.reloadData()
            }
          }
        }
      })
    },
    // 添加分析数据
    goInspect(row) {
      uni.navigateTo({
        url: `/pages/jobSlip/execute/analyse?ticketId=${row.ticketId}&nodeTaskId=${row.nodeTaskId}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          'callback:success': (data) => {
            if (data) {
              this.reloadData()
            }
          }
        }
      })
    },
    async goAcceptance(row) {
      let rew = await this.positionValidate(row.ticketId)
      console.log('r', rew)

      if (rew) return

      uni.navigateTo({
        url: `/pages/jobSlip/execute/acceptance?ticketId=${row.ticketId}&nodeTaskId=${row.nodeTaskId}&specialWorkType=${row.workTypeFlag}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          'callback:success': (data) => {
            if (data) {
              this.reloadData()
            }
          }
        }
      })
    },
    showSignature(row) {
      this.addPersonalForm.ticketId = row.ticketId
      this.signType = 1
      this.isPullDown(false)
      this.$refs.signature.open()
    },
    onSignatureSuccess(tempFilePath) {
      this.isPullDown(true)
      if (this.signType == 1) {
        addWorkPersonal({
          ...this.addPersonalForm,
          signatureUrls: this.signatureUrl
        }).then((res) => {
          this.$modal.showToast('新增作业人员成功')
        })
      }
      if (this.signType == 2) {
        updateGuardian({
          ...this.changeGuardianForm,
          signatureUrls: this.signatureUrl
        }).then((res) => {
          this.$modal.showToast('更换监护人成功')
          this.reloadData()
        })
      }
    },
    showUserSelect(row) {
      this.$refs.userSelectorRef.open()
      this.changeGuardianForm.ticketId = row.ticketId
      this.changeGuardianForm.taskId = row.nodeTaskId
    },
    userSelectorChange(obj) {
      if (!Object.keys(obj).length) {
        this.$modal.showToast('请选择监护人')
        return
      }
      this.changeGuardianForm.staffId = obj.value
      this.signType = 2
      this.isPullDown(false)
      this.$refs.signature.open()
    },
    transferTicket(item) {
      this.transferForm.taskId = item.nodeTaskId
      this.transferForm.nodeId = item.nodeId
      this.transferForm.procInstId = item.procInsId
      this.$refs.transferSelectorRef.open()
    },
    async transferSelectorChange(obj) {
      this.transferForm.toAssignee = obj.value
      this.$modal.confirm(`确定将任务转给【${obj.name}】吗？`).then(() => {
        turnTicket(this.transferForm).then(() => {
          this.$modal.showToast('转办成功')
          this.reloadData()
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.button-wrap-todo {
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .button-wrap-left {
    display: flex;
    align-items: center;

    > view {
      margin-right: 16rpx;
      margin-left: 0;
    }
  }
}

.affix {
  //width: 90px;
  height: 30px;
  position: absolute;
  top: 0;
  right: 0;
}

uni-image.affix-icon {
  height: 30px !important;
  width: 78px !important;
}

.button-wrap {
  .status-button {
    border: 1rpx solid #88b4c4;
    color: #88b4c4;

    &.active {
      border: 1rpx solid #c87c32;
      color: #c87c32;
    }
  }
}

.cu-card-wrap {
  margin-bottom: 24rpx;
  position: relative;

  &:first-child {
    margin-top: 24rpx;
  }
}

.icon-more {
  width: 32rpx;
  height: 32rpx;
  vertical-align: sub;
}

.more-button-wrap {
  display: flex;
  flex-wrap: wrap;

  .button {
    border-radius: 32rpx;
    border: 1rpx solid #454a5e;
    padding: 0 42rpx;
    color: #454a5e;
    line-height: 60rpx;
    height: 60rpx;
    font-size: 28rpx;
    margin-top: 20rpx;
    margin-right: 20rpx;
  }
}

.more-button {
  font-size: 28rpx;
  font-weight: 400;
  color: #999999;
  line-height: 60rpx;
  height: 60rpx;
}
</style>
